package com.factory.rest.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.factory.common.bean.Alarm;
import com.factory.common.bean.Algorithm;
import com.factory.common.bean.User;
import com.factory.common.core.SqlCondition;
import com.factory.common.pojo.QueryListParam;
import com.factory.common.pojo.Result;
import com.factory.common.pojo.UpdateWrapperBody;
import com.factory.common.utils.DateUtil;
import com.factory.common.utils.StringUtil;
import com.factory.rest.feign.AlarmClient;
import com.factory.rest.feign.BaseFeignClient;
import com.factory.rest.service.AlgorithmService;
import com.factory.rest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 告警模块相关的接口
 *
 * @author JW
 * @version 1.0
 * @date 2020/11/25 11:16
 */
@RestController
@RequestMapping("/rest/alarm")
public class AlarmController extends BaseFeignController<Alarm> {

    @Autowired
    private AlarmClient alarmClient;

    @Autowired
    private UserService userService;

    @Autowired
    private AlgorithmService algorithmService;

    @Override
    protected BaseFeignClient getBaseFeignClient() {
        return alarmClient;
    }

    /**
     * 查询告警信息接口
     *
     * @param param
     * @return
     */
    @Override
    public Result queryList(@RequestBody QueryListParam param) {
        log.info("查询告警信息接口,{}", param);

        User user = userService.getLoginUser().get();

        List<SqlCondition> conditions = param.getConditions();
        conditions.add(new SqlCondition("userId", user.getId(), SqlCondition.Conditions.EQ));
        conditions.add(new SqlCondition("createDate", "createDate", SqlCondition.Conditions.DESC));

        return alarmClient.queryList(param);
    }

    /**
     * 告警数据统计
     *
     * @return
     */
    @RequestMapping("/statistics")
    public Result statistics() {
        log.info("设备数据统计");

        User user = userService.getLoginUser().get();
        var params = new HashMap<String, Object>();
        params.put("userId", user.getId());

        return alarmClient.statistics(params);
    }

    /**
     * 告警信息统计
     *
     * @param params
     * @return
     */
    @PostMapping("/statisticsAlarm")
    public Result statisticsAlarm(@RequestBody Map<String, Object> params) {
        log.info("告警信息统计,{}", params);

        User user = userService.getLoginUser().get();
        params.put("userId", user.getId());
        List<Algorithm> algorithms = algorithmService.selectList(new QueryWrapper<Algorithm>().ge("status", 0));
        params.put("algorithms", algorithms);

        return alarmClient.statisticsAlarm(params);
    }

    /**
     * 日统计告警信息统计
     *
     * @param params
     * @return
     */
    @PostMapping("/statisticsDay")
    public Result statisticsDay(@RequestBody Map<String, Object> params) {
        log.info("日统计告警信息统计,{}", params);
        User user = userService.getLoginUser().get();
        params.put("userId", user.getId());
        params.put("beginDate", DateUtil.getDateString(DateUtil.getDate(-1)));

        List<Algorithm> algorithms = algorithmService.selectList(new QueryWrapper<Algorithm>().ge("status", 0));
        params.put("algorithms", algorithms);

        Map<String, Object> result = new HashMap<>();
        Result result1 = alarmClient.statisticsDay(params);

        if (result1.isStatus()) {
            result.put("statistics", result1.getData());
            List<String> hoursStrings = DateUtil.getHoursStrings(24, "HH:00");
            Collections.reverse(hoursStrings);
            result.put("date", hoursStrings);
            return Result.success(result);
        }

        return Result.fail("失败!");
    }

    /**
     * 周统计告警信息统计
     *
     * @param params
     * @return
     */
    @PostMapping("/statisticsWeek")
    public Result statisticsWeek(@RequestBody Map<String, Object> params) {
        log.info("周统计告警信息统计,{}", params);
        User user = userService.getLoginUser().get();
        params.put("userId", user.getId());
        params.put("beginDate", DateUtil.getDateString(DateUtil.getDate(-7)));

        List<Algorithm> algorithms = algorithmService.selectList(new QueryWrapper<Algorithm>().ge("status", 0));
        params.put("algorithms", algorithms);

        Result result1 = alarmClient.statisticsWeek(params);
        if (result1.isStatus()) {
            Map<String, Object> result = new HashMap<>();
            result.put("statistics", result1.getData());
            List<String> weeksStrings = DateUtil.getWeeksStrings(7, "");
            Collections.reverse(weeksStrings);
            result.put("date", weeksStrings);
            return Result.success(result);
        }

        return Result.fail("失败!");
    }

    /**
     * 周统计告警信息统计
     *
     * @param params
     * @return
     */
    @PostMapping("/statisticsMonth")
    public Result statisticsMonth(@RequestBody Map<String, Object> params) {
        log.info("周统计告警信息统计,{}", params);
        User user = userService.getLoginUser().get();
        params.put("userId", user.getId());

        String regex = "^\\d{4}[-]([0][1-9]|(1[0-2]))[-]([1-9]|([012]\\d)|(3[01]))([ \\t\\n\\x0B\\f\\r])(([0-1]{1}[0-9]{1})|([2]{1}[0-4]{1}))([:])(([0-5]{1}[0-9]{1}|[6]{1}[0]{1}))([:])((([0-5]{1}[0-9]{1}|[6]{1}[0]{1})))$";

        if (StringUtil.isEmpty(params.get("beginDate"))) {
            params.put("beginDate", DateUtil.getDateString(DateUtil.getDate(-30)));
        } else if (!StringUtil.matches(params.get("beginDate"), regex)) {
            return Result.fail("beginDate 格式不正确!");
        }

        if (StringUtil.notEmpty("endDate") && !StringUtil.matches(params.get("beginDate"), regex)) {
            return Result.fail("endDate 格式不正确!");
        }

        long day = 30;
        Date date = new Date();
        if (StringUtil.notEmpty(params.get("endDate"))) {
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime endDate = LocalDateTime.parse(params.get("endDate").toString(), dateTimeFormatter);
            date = Date.from(endDate.atZone(ZoneId.systemDefault()).toInstant());
            day = Duration.between(LocalDateTime.parse(params.get("beginDate").toString(), dateTimeFormatter),
                    endDate).toDays();
        }

        List<Algorithm> algorithms = algorithmService.selectList(new QueryWrapper<Algorithm>().ge("status", 0));
        params.put("algorithms", algorithms);


        Result result1 = alarmClient.statisticsMonth(params);
        if (result1.isStatus()) {
            Map<String, Object> result = new HashMap<>();
            result.put("statistics", result1.getData());
            List<String> dayStrings = DateUtil.getDayStrings(date, (int) day, "MM-dd");
            Collections.reverse(dayStrings);
            result.put("date", dayStrings);
            return Result.success(result);
        }

        return Result.fail("失败!");
    }

    /**
     * 年统计告警信息统计
     *
     * @param params
     * @return
     */
    @PostMapping("/statisticsQuarter")
    public Result statisticsQuarter(@RequestBody Map<String, Object> params) {
        log.info("年统计告警信息统计,{}", params);

        User user = userService.getLoginUser().get();
        params.put("userId", user.getId());

        List<Algorithm> algorithms = algorithmService.selectList(new QueryWrapper<Algorithm>().ge("status", 0));
        params.put("algorithms", algorithms);

        Result result1 = alarmClient.statisticsQuarter(params);
        if (result1.isStatus()) {
            Map<String, Object> result = new HashMap<>();
            result.put("statistics", result1.getData());
            return Result.success(result);
        }

        return Result.fail("失败!");
    }

    /**
     * 全部清理告警数据统计
     *
     * @return
     */
    @GetMapping("/closeAll")
    public Result closeAll() {
        log.info("全部清理告警数据统计");
        Alarm alarm = new Alarm();
        alarm.setStatus(1);

        UpdateWrapperBody<Alarm> updateWrapperBody = new UpdateWrapperBody<>();
        updateWrapperBody.setT(alarm);
        updateWrapperBody.setUpdateWrapper(new UpdateWrapper<Alarm>().eq("userId", userService.getLoginUser().get().getId()));

        return Result.success(alarmClient.updateWrapper(updateWrapperBody));
    }
}
